package com.warehouse.controller;

import com.warehouse.common.Result;
import com.warehouse.entity.Customer;
import com.warehouse.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/customers")
@CrossOrigin(origins = "*")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @GetMapping
    public Result<List<Customer>> getAllCustomers() {
        List<Customer> customers = customerService.getAllCustomers();
        return Result.success(customers);
    }

    @GetMapping("/active")
    public Result<List<Customer>> getActiveCustomers() {
        List<Customer> customers = customerService.getActiveCustomers();
        return Result.success(customers);
    }

    @GetMapping("/{id}")
    public Result<Customer> getCustomerById(@PathVariable Long id) {
        Customer customer = customerService.getCustomerById(id);
        if (customer != null) {
            return Result.success(customer);
        }
        return Result.error("客户不存在");
    }

    @GetMapping("/search/name")
    public Result<List<Customer>> searchCustomersByName(@RequestParam String customerName) {
        List<Customer> customers = customerService.getCustomersByName(customerName);
        return Result.success(customers);
    }

    @GetMapping("/search/phone")
    public Result<List<Customer>> searchCustomersByPhone(@RequestParam String phone) {
        List<Customer> customers = customerService.getCustomersByPhone(phone);
        return Result.success(customers);
    }

    @PostMapping
    public Result<Customer> createCustomer(@RequestBody Customer customer) {
        Customer createdCustomer = customerService.createCustomer(customer);
        return Result.success(createdCustomer);
    }

    @PutMapping("/{id}")
    public Result<Customer> updateCustomer(@PathVariable Long id, @RequestBody Customer customer) {
        customer.setId(id);
        Customer updatedCustomer = customerService.updateCustomer(customer);
        return Result.success(updatedCustomer);
    }

    @PutMapping("/{id}/status")
    public Result<Boolean> updateCustomerStatus(@PathVariable Long id, @RequestParam String status) {
        boolean success = customerService.updateCustomerStatus(id, status);
        if (success) {
            return Result.success(true);
        }
        return Result.error("更新客户状态失败");
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCustomer(@PathVariable Long id) {
        boolean success = customerService.deleteCustomer(id);
        if (success) {
            return Result.success(true);
        }
        return Result.error("删除客户失败");
    }
    
    @GetMapping("/count")
    public Result<Long> getCustomerCount() {
        long count = customerService.getCustomerCount();
        return Result.success(count);
    }
} 